package org.itboys.weixin.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.EasyUiTreeDO;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.collection.CommonCollectionUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.weixin.dto.SendArticle;
import org.itboys.weixin.entity.SendWeixinMessage;
import org.itboys.weixin.entity.SendWeixinMessageDetail;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinSendRecord;
import org.itboys.weixin.service.SendWeixinMessageDetailService;
import org.itboys.weixin.service.SendWeixinMessageService;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.service.WeixinPush;
import org.itboys.weixin.service.WeixinSendRecordService;
import org.itboys.weixin.tools.WeixinSendUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@RestController
@RequestMapping(value = "/weixin/sendmessage")
public class SendWeixinMessageController extends BaseController {

	/**
	 * 加载所有栏目页面上显示
	 * 
	 * @return
	 */
	@Autowired
	private SendWeixinMessageService sendWeixinMessageService;
	@Autowired
	private SendWeixinMessageDetailService sendWeixinMessageDetailService;
	@Autowired
	private WeixinPush weixinPush;
	@Autowired
	private WeixinConfigService weixinConfigService;
	@Autowired
	private WeixinSendRecordService weixinSendRecordService;
	@Autowired
	private ResourceHolder resourceHolder;

	@RequestMapping("/vm")
	public ModelAndView projectMenus(HttpServletRequest request, Model model) {
		return new ModelAndView("/weixin/sendmessage/list");
	}

	@RequestMapping("/list")
	public void list(HttpServletResponse response, HttpServletRequest request) {
		Page<SendWeixinMessage> page = sendWeixinMessageService
				.pageQuery(request);
		JsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	@RequestMapping("/getById")
	public ModelAndView getById(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String id = request.getParameter("id");
		if (StringUtils.isNotBlank(id)) {
			SendWeixinMessage entity = sendWeixinMessageService.getById(Long
					.valueOf(id));
			model.addAttribute("entity", entity);
		}
		/*model.addAttribute("staticRoot",resourceHolder.getStringValue("staticRoot"));
		model.addAttribute("adminRoot",resourceHolder.getStringValue("adminRoot"));
		model.addAttribute("imgRoot",resourceHolder.getStringValue("imgRoot"));*/
		return new ModelAndView("/weixin/sendmessage/input");
	}

	@RequestMapping("/save")
	public void insert(HttpServletResponse response,
			@ModelAttribute SendWeixinMessage sendWeixinMessage) {
		try {
			if (sendWeixinMessage.getId() == 0L) {
				sendWeixinMessageService.save(sendWeixinMessage);
				AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			} else {
				sendWeixinMessageService.update(sendWeixinMessage);
				AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	@RequestMapping("/delete")
	public void delete(HttpServletResponse response, HttpServletRequest request) {
		try {
			Long id = Long.valueOf(request.getParameter("id"));
			AjaxUtils.renderText(response,
					String.valueOf(sendWeixinMessageService.delete(id)));
		} catch (Exception e) {
			AjaxUtils.renderJson(response, 0);
		}
	}

	@RequestMapping("/getlist")
	public void getList(HttpServletResponse response, HttpServletRequest request) {
		try {
			// Long weixinId = Long.valueOf(request.getParameter("weixinId"));
			Map<String, Object> sqlMap = Maps.newHashMap();
			// sqlMap.put("weixinId", weixinId);
			List<SendWeixinMessage> wmlist = sendWeixinMessageService
					.list(sqlMap);
			AjaxUtils.renderJson(response, wmlist);
		} catch (Exception e) {
			AjaxUtils.renderJson(response, 0);
		}
	}

	/**
	 * 获取微信号树 并全选中
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("getWeixinConfigTree")
	public void getWeixinConfigTree(HttpServletResponse response) {
		// Long
		// projectId=ServletContextHolder.getSession().getAttribute(WebConstants.SessionKey.PROJECT_ID)==null?0l:SessionHolder.getProjectId();
		List<WeixinConfig> modules = weixinConfigService
				.getByParentIdAndProjectId(0l);// 获取具有权限的模板
		List<EasyUiTreeDO> tree = Lists
				.newArrayListWithCapacity(modules.size());

		for (WeixinConfig am : modules) {
			EasyUiTreeDO module = new EasyUiTreeDO();
			module.setId(am.getId());
			module.setText(am.getName());
			module.setChecked(true);
			module.setChildren(prepareChildren(am.getId()));
			tree.add(module);
		}
		AjaxUtils.renderJson(response, tree);
	}

	public List<EasyUiTreeDO> prepareChildren(Long parentId) {
		List<EasyUiTreeDO> module = Lists.newArrayList();
		List<WeixinConfig> children = Lists.newArrayList();
		if (weixinConfigService.getByParentIdAndProjectId(parentId).size() > 0) {
			children = weixinConfigService.getByParentIdAndProjectId(parentId);
			for (WeixinConfig wc : children) {
				EasyUiTreeDO permission = new EasyUiTreeDO();
				permission.setId(wc.getId());
				permission.setText(wc.getName());
				permission.setChecked(true);
				permission.setChildren(prepareChildren(wc.getId()));
				module.add(permission);
			}
		}
		return module;
	}

	@RequestMapping("/dosend")
	public void doSend(HttpServletResponse response, HttpServletRequest request) {
		try {
			Integer isTest = 0;
			if (StringUtils.isNotBlank(request.getParameter("isTest"))) {
				isTest = Integer.valueOf(request.getParameter("isTest"));
			}
			String str = request.getParameter("weixinIds");
			List<Long> weixinIds = CommonCollectionUtils.splictToLongList(str,
					",");
			Long wxMsgId = Long.valueOf(request.getParameter("wxMsgId"));
			SendWeixinMessage swm = sendWeixinMessageService.getById(wxMsgId);
			Map<String, Object> sqlMap = Maps.newHashMap();
			sqlMap.put("wxMsgId", wxMsgId);
			List<SendWeixinMessageDetail> wmlist = sendWeixinMessageDetailService
					.list(sqlMap);
			WeixinSendRecord weixinSendRecord = new WeixinSendRecord();

			if (wmlist.size() >= 1) {
				if (swm.getMsgType() == 1) {
					for (Long weixinId : weixinIds) {
						weixinSendRecord.setSendMsgId(wxMsgId);
						weixinSendRecord.setWeixinId(weixinId);
						weixinSendRecordService.save(weixinSendRecord);
						weixinPush.doSend(weixinSendRecord.getId(), weixinId,
								wmlist.get(0).getContent(), isTest);
					}
				} else {
					List<SendArticle> articles = WeixinSendUtils.getArticles(
							wmlist, resourceHolder.getStringValue("imgRoot"));
					for (Long weixinId : weixinIds) {
						weixinSendRecord.setSendMsgId(wxMsgId);
						weixinSendRecord.setWeixinId(weixinId);
						weixinSendRecordService.save(weixinSendRecord);
						weixinPush.doSend(weixinSendRecord.getId(), weixinId,
								articles, isTest);
					}
				}
				AjaxUtils.renderJson(response, 1);
			} else {
				AjaxUtils.renderJson(response, -1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AjaxUtils.renderJson(response, 0);
		}
	}
}
